<?php

/*
	This file is part of Mandragon.

    Mandragon is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Mandragon is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Mandragon.  If not, see <http://www.gnu.org/licenses/>.
*/

class ItemFunctions {

	private $access;
	private $toolbox;
	private $db_access;
	private $creator;
	private $checker;
	private $alerter;
	
	public function __construct() {
		$this->toolbox = new Toolbox();
		$this->access = new AccessManager();
		$this->db_access = new DbAccessor();
		$this->creator = new FormCreator();
		$this->checker = new InputChecker();
		$this->alerter = new Alerter();
	}

	public function set_toolbox($toolbox) {
		$this->toolbox = $toolbox;
	}

	public function set_db_accessor($db_access) {
		$this->db_access = $db_access;
	}

	public function set_access_manager($access) {
		$this->access = $access;
	}

	function item_page_inc_check_access($page) {
		$this->access->check_access("READ");
		$this->item_page_inc_check_occurences($page);
	}

	function item_page_inc_check_occurences($page) {
		$THISDIR = $page->directory_tree[$page->dir_depth - 1];

		$dir_ok = 0;

		// fetch crosspost and plain locations
		$page->occurences = array();
		$occurences = $this->db_access->db_do_query($this->db_access->db_query_select(array(array(), "SUB_IN.*"), 
												  array("ITEM_IN INNER JOIN SUB_IN ON ITEM_IN.sub_id = SUB_IN.sub_id", "DUMMY"), 
												  "NOT ITEM_IN.deleted AND item_id = {$page->id}"));
		while ($occ = $this->db_access->db_fetch_array($occurences)) {
			if ($occ['dir_id'] == $THISDIR['dir_id'])
				$dir_ok = 1;
			$occarr = array();
			$dir = $occ['dir_id'];
			$link = "";
			while (($dir != 0) and ($page->menu[$dir]['access'] != "DENY")) {
				array_unshift($occarr, array('name' => $page->menu[$dir]['menuname'], 'link' => $page->menu[$dir]['name']));
				$dir = $page->menu[$dir]['parent_id'];
			}
			if ($page->menu[$dir]['access'] != "DENY") {
				$occarr[] = array('name' => $occ['sub_title'] ? $occ['sub_title'] : "Andere..", 'link' => "{$occ['sub_id']}.subset");
				$page->occurences[] = $occarr;
			}
		}

		if (!$dir_ok) {
			errorpage(11);
		}
	}


	function item_page_inc_execute_action($page, $action, $type) {
		$THISDIR = $page->directory_tree[$page->dir_depth-1];

		$itemAction = ItemAction::get_instance($action);
		$itemAction.execute();
	}


	function item_page_inc_execute($page, $type) {
		global $CONFIG;
		$THISDIR = $page->directory_tree[$page->dir_depth-1];
		$CONTENT = $page->content;
		
		$this->increase_hits($page);
		$type_props = $this->fetch_type_properties($type);
		$this->item_page_replying($page, $type_props);
		$this->item_page_scoring($page, $type_props);

		if ($_SESSION['user_id']) {
			$this->item_page_subscription_actions($page, $type);
			$this->item_page_mark_un_read($page);
			$this->item_page_moderator_n_owner($page);
			$this->item_page_moderator_only($page, $type);
		}
		
		if ($CONFIG['reply_mode'] == "reply") { 
			$this->item_page_fetch_replies($page);
		}
		
		$this->fetch_score($page, $type_props);

		$this->reply($page);
	}

	function item_page_fetch_replies($page) {
		global $CONFIG;

		$count = ($_SESSION['member']['pref_numposts'] ? $_SESSION['member']['pref_numposts'] : $CONFIG['numposts']);
		$limit = intval($_GET['offset']) . ", " . (intval($count) + 0);		
		$sql = $this->db_access->db_query_select(
				array(
						array(), 
						"POST.*, POST_BODY.*, M1.nick as nick_author, M2.nick as nick_editor, M1.signature as sig_author, M1.signature_spacer as sig_spacer_author, M1.title as title_author, M1.postcount as pc_author, M1.avatar_mini as mini_author, M1.avatar_maxi as maxi_author"), 
				array(
						"MEMBER AS M1, MEMBER AS M2, POST INNER JOIN POST_BODY ON POST.post_id = POST_BODY.post_id", 
						"DUMMY"), 
				"M1.user_id = POST.author AND M2.user_id = POST.editor AND POST.item_id = {$page->id} AND deleted = 0", 
				"creation ASC", 
				$limit);

		$sqlresult = $this->db_access->db_do_query($sql);
		$replies = array();
		$newest = 0;
		$rights = ($this->access->has_access("MODERATE") || $this->access->has_access("ADMIN"));
		while ($r = $this->db_access->db_fetch_array($sqlresult)) {
			if ($r['signature']) {
				$separator = "";
				if($r['sig_spacer_author'] == 2) {
					$separator = "<br /><br /><br />"; //TODO: move this to a template, adjustable in the skin
				} elseif($r['sig_spacer_author'] == 3) {
					$separator = "<hr class=\"signature\" />"; //TODO: move this to a template, adjustable in the skin
				}
				$r['signedbody'] = $r['body'] . $separator . $r['sig_author'];
				$r['separator'] = $separator;
			} else {
				$r['signedbody'] = $r['body'];
			}
			if ($rights or ($r['author'] == $_SESSION['user_id'])) {
				//TODO: extract javascript
				$r['delete_url'] = "javascript:popup('{$page->id}.delete?type=REPLY&ids={$r['post_id']}',300,200);";
				$r['edit_url'] = "?action=edit_reply&id={$r['post_id']}";
				$r['mass_delete'] = $rights;
			} 
			if (!$newest and ($_SESSION['member']['last_visit'] < max($r['edit'], $r['creation']))) {
				$r['newest'] = 1;
				$newest = 1;
			}
			array_unshift($replies, $r);
		}
		
		$page->content['replies'] = $replies;
	}

	function item_page_moderator_only($page, $type) {
		// moderator only
		if ($this->access->has_access("MODERATE") or $this->access->has_access("ADMIN")) {
			
			// movement
			$this->toolbox->add_action($page, 'move', 'popup', "{$page->dir_path}/{$page->id}.move");
			
			// deletion
			$this->toolbox->add_action($page, 'delete', 'popup', "{$page->dir_path}/{$page->id}.delete?type=ITEM&ids={$page->id}");
			
			// mass post actions
			//TODO: extract javascript
			$this->toolbox->add_action($page, 'posts-delete', 'javascript', '', 'selected_delete();');
			$this->toolbox->add_action($page, 'posts-move', 'javascript', '', 'selected_move();');
			
			// stickiness
			$this->toolbox->add_action($page, 'unstick', 'url-action', !$page->content[$type]['sticky'] ? 'stick' : 'unstick');

			// open/closed
			$this->toolbox->add_action($page, 'item-close', 'url-action', $page->content[$type]['closed'] ? 'open' : 'close');
		}
	}

	function item_page_moderator_n_owner($page) {
		if ($_SESSION['user_id'] == $page->content['owner'] 
				|| $this->access->has_access("MODERATE") 
				|| $this->access->has_access("ADMIN")) {	
			// edits
			$this->toolbox->add_action($page, 'edit_item', 'url', "{$page->id}.edit_item");
		}
	}

	function item_page_mark_un_read($page) {
		$THISDIR = $page->directory_tree[$page->dir_depth-1];

		if ($_SESSION['member']['pref_auto_mark_read'] and !($_GET['action'] == "markunread")) {
			$sql = $this->db_access->db_query_insert_multiple(array('user_id', 'item_id'), 
											array(array($_SESSION['user_id'], 
											$page->id)), "HAS_READ", 1);
			$this->db_access->db_do_query($sql);
			$n = $this->db_access->db_affected_rows();
			$page->menu[$THISDIR['dir_id']]['new_items'] -= $n;
			$page->menu[$THISDIR['dir_id']]['read_items'] += $n;
			$this->toolbox->add_action($page, 'unread_item', 'url-action', "markunread");
		} else if ($_SESSION['user_id']) {
			$this->toolbox->add_action($page, 'read_item', 'url-action', "markread");
		}
	}

	function item_page_scoring($page, $type_props) {
		if ($type_props['can_be_scored']) {
			if ($this->access->has_access("REPLY")) {
				$this->toolbox->add_action($page, 'score', 'url-action', "score", "", 1);
			}
		}
	}
		
	function item_page_replying($page, $type_props) {
		$toolbox = new Toolbox();
		if ($type_props['can_be_replied']) {
			if ($this->access->has_access("REPLY") and !$CONTENT[$type]['closed']) {
				$toolbox->add_action($page, 'reply', 'javascript', '', "reply2()", 1); //TODO: extract javascript
			}
		}
	}

	function fetch_type_properties($type) {
		$db_access = new DbAccessor();
		return $db_access->db_fetch_array($db_access->db_do_query($db_access->db_query_select(array(array('*')), 
							  array('ITEM_TYPE'), "extension = '$type'")));
	}

	function increase_hits($page) {
		$db_access = new DbAccessor();
		$sql = $db_access->db_query_update(array('hits', 'creation', 'edit'), 
							   array('hits+1', 'creation', 'edit'), 
							   "ITEM", "item_id = {$page->id}");
		$db_access->db_do_query($sql);
	}

	function item_page_subscription_actions($page, $type) {
		$db_access = new DbAccessor();
		$toolbox = new Toolbox();
		$sql = $db_access->db_query_select(array(array('*')), array("SUBSCRIBE_ITEM"), 
							   "item_id = {$page->id} AND user_id = {$_SESSION[user_id]}");
		if ($db_access->db_num_rows($db_access->db_do_query($sql)) == 0) {
			$toolbox->add_action($page, 'subscribe_item', 'popup', 
					   "{$page->dir_path}/{$page->id}.subscribe");
		} else {
			$toolbox->add_action($page, 'altersubscription_item', 'popup', 
					   "{$page->dir_path}/{$page->content[$type]['item_id']}.subscribe");
		}
	}

	function fetch_score($page, $type_props) {
		if ($type_props['can_be_scored']) {
		
			$score = array();
			$score['max'] = $type_props['can_be_scored'];
			$r = $this->db_access->db_fetch_array(
					$this->db_access->db_do_query(
							"SELECT AVG(score) AS score, COUNT(item_id) AS count FROM ITEM_SCORE WHERE item_id = {$page->id}"));
			$score['score'] = round(doubleval($r['score']), 2);
			$score['count'] = $r['count'];
		
			if ($type_props['can_be_commented']) {
			
				$comments = array();
			
				$sqlres = $this->db_access->db_do_query(
						$this->db_access->db_query_select(
								array(
									array('*'), 
									array('nick', 'avatar_mini')), 
								array('ITEM_SCORE', 'MEMBER'), 
								"ITEM_SCORE.user_id = MEMBER.user_id AND ITEM_SCORE.item_id = {$page->id}"));
				if ($this->db_access->db_num_rows($sqlres)) {
					while ($c = $this->db_access->db_fetch_array($sqlres)) {
						$comments[] = $c;
					}
				}
			
				$score['comments'] = $comments;
			}
			$page->content['score'] = $score;
		}
	}

	function item_page_inc_dress_before($page) {
		global $CONFIG;
		print_occurences($page, $page->occurences);
		if ($page->scoreform) {
			print_form($page, $page->scoreform);
		}
		print_replyform($page, $page->content['replyform'], intval($_POST['replying']) or ($_GET['action'] == "edit_reply"));
	}

	function item_page_inc_dress_after($page) {
		global $CONFIG;
		if ($page->content['score']) {
			print_score($page, $page->content['score']);
		}
		print_replies($page, $page->content['replies'], $page->content[$page->type], $page->fullpath);
		print_occurences($page, $page->occurences);
	}

	function exec_if_new($inputs) {
		$sql = $this->db_access->db_query_select(array(array("*"), array("*")), 
				   array("ITEM_TYPE", "ACCESS_ACTION"), 
				   "add_action_id = action_id", "item_type_id ASC");
		$keys = array();
		$values = array();
		$info = array();
		$result = $this->db_access->db_do_query($sql);
		while ($r = $this->db_access->db_fetch_array($result)) {
			if ($this->access->has_access($r['action'])) {
				$keys[] = $r['item_type_id'];
				$values[] = $r['name'];
				$info[] = $r['info'];
			}
		}
		$inputs[] = $this->creator->input_select("Type item", "item_type_id", $keys, $values, "selecteer type", $_POST['item_type_id']); 

		if (!$_POST['item_type_id']) {
			$inputs[] = $this->creator->info("<ul class=\"itemhelplist\"><li>" . implode($info, "<li>") . 
					  "</ul>", 1, 'meer info');
			//TODO: move HTML to skin
		}
		return $inputs;
	}

	function exec_show_subset($page, $inputs, $item) {
		// subset
		$sql = $this->db_access->db_query_select(array(array("*")), array("SUB_IN"), 
							   "SUB_IN.dir_id = {$page->directory_tree[$page->dir_depth-1]['dir_id']}", 
							   "sub_title ASC");
		$sqlresult = $this->db_access->db_do_query($sql);
		$keys = array();
		$values = array();
		$default = "";
		while ($r = $this->db_access->db_fetch_array($sqlresult)) {
			$keys[] = $r['sub_id'];
			if ($new and !$r['sub_title'])
				$default = $r['sub_id'];
			$title = $r['sub_title'];
			if (strlen($title) > 30)
				$title = substr($title, 0, 30) . "&hellip;";
			$values[] = $title;
		}
		if ($_GET['sub_id']) {
			$default = $_GET['sub_id'];
		}
		$keys[] = "NEW";
		$values[] = $_POST['new_subset'] ? $_POST['new_subset'] : "NIEUWE SET";
		$inputs[] = $this->creator->input_select("Subset", "sub_id", $keys, $values, 
					  $new ? "selecteer een categorie" : "", 
					  $new ? $default : $item['sub_id'], 
					  "document.itemform.submit()");
					  //TODO: replace with regular button
		
		if ($_POST['sub_id'] == "NEW") {
			$inputs[] = $this->creator->input_field("Nieuwe subset", "new_subset", "", "", "", "");
		}
		return $inputs;
	}


	function item_form($page, $item = "") {
		$inputs = array();

		$new = ($item == "");

		// if $item is set, it should be an array containing all item info
		if (!$new and !is_array($item)) {
			errorpage(7);
		}
		
		$inputs[] = $this->creator->header($page->content['title'] ? $page->content['title'] : ($new ? "Een item toevoegen" : "Een item aanpassen"));
		
		// item id
		$inputs[] = $this->creator->input_hidden("item_id", $new ? "NEW" : $item['item_id']);
		
		// item type if new
		if ($new) {
			$inputs = $this->exec_if_new($inputs);
		}
		
		if (!$new or $_POST['item_type_id']) {
		
			$inputs = $this->exec_show_subset($page, $inputs, $item);
			
			// item title
			$inputs[] = $this->creator->input_field("Titel", "title", $this->db_access->db_desqlize($item['title']));

			// item-dependent stuff
			$topic = BaseTopic::new_topic($page, $new, $item);
			$inputs = $topic->prepare($new, $item, $inputs);
		}
		
		if (!$new) {
			$inputs[] = $this->creator->input_checkbox("Markeer als nieuw", "mark_new", 0, "", 0, 1);
		}
		
		$page->content['form'] = $this->creator->create("itemform", array_reverse($inputs), $_SERVER['PATH_INFO'], "POST", "", "multipart/form-data");
	}

	/**
	 * perform checks on the input
	 */
	function item_page_inc_check_content($page, $values, $files, $type, $new = 0) {
		
		global $filename, $CONFIG;

		$ok = true;
		
		if ($type != "fiche") {
			$ok = $ok && $this->checker->checkExistsAndTags($values, 'title', 'titel');	
		}
		
		if ($values['sub_id'] == "NEW") {
			$ok = $this->checker->checkNew($ok, $values);
		} else if ($values['sub_id'] <= 0) {
			$ok = false;
			$this->alerter->add_alert("Geen subset gekozen");
		}

		$baseTopic = BaseTopic::get_instance($page, $type);
		return $ok && $baseTopic->check_content($values, $new);
	}

	function reply($page) {

		global $CONFIG;
		$THISDIR = $page->directory_tree[$page->dir_depth-1];
		
		if ($_GET['action'] == "edit_reply") {
		
			$reply_id = $_GET['id'];
		
			$sql = $this->db_access->db_query_select(array(array(), "POST.*, POST_BODY.*"), 
						  array("POST INNER JOIN POST_BODY on POST.post_id = POST_BODY.post_id", "DUMMY"), "POST.post_id = {$reply_id}");
			$sqlresult = $this->db_access->db_do_query($page, $sql);
			if ($this->db_access->db_num_rows($sqlresult) != 1) {
				errorpage(404);
			}
			
			$reply = $this->db_access->db_fetch_array($sqlresult);
			
			// check access
			if (($reply['author'] != $_SESSION['user_id']) && !$this->access->has_access("MODERATE") && !$this->access->has_access("ADMIN")) {
				errorpage(5);
			}
		}

		if ($_POST['submitted'] and $_POST['replying']) {

			if ($page->content[$page->type]['closed']) {
				errorpage(13);
			}
		
			$ok = ($this->checker->check_exists($_POST['body'], "reactie") 
				&& $this->checker->check_tags_advanced($_POST['body'], "reactie") 
				&& $this->checker->check_tag_closures($_POST['body']));

			if($ok) {
				$_POST['title'] = '---'; //Temporary workaround between versions. Currently title should no longer be used for reply-forms
			}

			if ($reply_id) { // edit reply
										
				if ($ok) {
					$sql = $this->db_access->db_query_update(array('body'), array($db_access->db_sqlize($_POST['body'])), "POST_BODY", "post_id = {$reply_id}");
					$this->db_access->db_do_query($sql);
					$sql = $this->db_access->db_query_update(array('title', 'editor', 'creation', 'edit', 'signature'), array($db_access->db_sqlize($_POST['title']), ($_POST['mark_new'] ? $_SESSION['user_id'] : "editor"), 'creation', ($_POST['mark_new'] ? "NOW(14)" : "edit"), ($_POST['use_signature'] ? 1 : 0)), "POST", "post_id = {$reply_id}");
					$this->db_access->db_do_query($sql);
					if ($_POST['mark_new']) {
						$sql = $this->db_access->db_query_update(array('editor', 'edit'), array($_SESSION['user_id'], "NOW(14)"), "ITEM", "item_id = {$reply['item_id']}");
						$this->db_access->db_do_query($sql);
						$this->db_access->db_do_query($db_access->db_query_delete("HAS_READ", "item_id = {$page->id}"));
					}
					redirect($page->fullpath);
				}
				
			} else { // insert new reply form
				
				if ($ok) {
				
					$sql = $this->db_access->db_query_insert(
							array('item_id', 'author', 'editor', 'title', 'creation', 'edit', 'postcount', 'signature'), 
							array($page->id, $_SESSION['user_id'], $_SESSION['user_id'], $this->db_access->db_sqlize($_POST['title']), 
							'NOW(14)', 
							'NOW(14)', 
							(intval($_SESSION['member']['postcount']) + 1), 
							($_POST['use_signature'] ? 1 : 0)), "POST");
					$this->db_access->db_do_query($sql);
					$post_id = $this->db_access->db_insert_id();
					
					$sql = $this->db_access->db_query_insert(array('post_id', 'body'), array($post_id, $this->db_access->db_sqlize($_POST['body'])), "POST_BODY");
					$this->db_access->db_do_query($sql);
					
					$sql = $this->db_access->db_query_update(array('editor', 'edit', 'creation', 'num_posts'), array($_SESSION['user_id'], 'NOW(14)', 'creation', 'num_posts+1'), "ITEM", "item_id = {$page->id}");
					$this->db_access->db_do_query($sql);
									
					$_SESSION['member']['postcount'] = (intval($_SESSION['member']['postcount']) + 1);
					if ($_SESSION['member']['title'] == "boomdraak") {
						$sql = $this->db_access->db_query_update(
								array('postcount', 'member_since', 'last_visit', 'title'), 
								array('postcount+1', 'member_since', 'last_visit', $this->db_access->db_sqlize("draak")), 
								"MEMBER", 
								"user_id = {$_SESSION['user_id']}");
					} else {
						$sql = $this->db_access->db_query_update(array('postcount', 'member_since', 'last_visit'), array('postcount+1', 'member_since', 'last_visit'), "MEMBER", "user_id = {$_SESSION['user_id']}");
					}
					$this->db_access->db_do_query($sql);
				
					$this->db_access->db_do_query($this->db_access->db_query_delete("HAS_READ", "item_id = {$page->id}"));
					
					// handle subscriptions
					$message = array(
						'alert' => "{$_SESSION['member']['nick']} plaatste een reactie bij <a href={$page->fullpath}#new>item #{$page->id}</a> '{$page->content['title']}'. <span class=iteminfo>(je krijgt dit bericht omdat je je abonneerde op dat item. Vanop de pagina van het item zelf kan je je abonnement opzeggen)</span>",
						'subject' => "Reactie op item #{$page->id}",
						'mail' => "{$_SESSION['member']['nick']} plaatste een reactie bij <a href={$page->fullpath}#new>item #{$page->id}</a> '{$page->content['title']}'\n<quote author={$_SESSION['member']['nick']}>{$_POST['body']}</quote>\n<p>(je krijgt dit bericht omdat je je abonneerde op dat item. Vanop de pagina van het item zelf kan je je abonnement opzeggen)",
						'email' => ereg_replace("<quote.+</quote>", "", "{$_SESSION['member']['nick']} plaatste een reactie bij item #{$page->id} '{$page->content['title']}'\nlink: {$CONFIG['base_url']}{$page->fullpath}#new\n\n---------------------\n{$_POST['body']}\n---------------------\n\n(je krijgt dit bericht omdat je je abonneerde op dat item. Vanop de pagina van het item zelf kan je je abonnement opzeggen)"));
					$this->handle_subscriptions("ITEM", $page->id, $message);

					$this->toolbox->redirect($page->fullpath);
				}
			}
		}

		$inputs = array();
		
		if (($this->access->has_access("MODERATE") || $this->access->has_access("ADMIN")) && $reply_id) {
			$inputs[] = $this->creator->input_checkbox("Markeer item als nieuw", "mark_new", 0);
		} else {
			$inputs[] = $this->creator->input_hidden("mark_new", 1);
		}
		
		$inputs[] = $this->creator->input_checkbox("Gebruik mijn ondertekening", "use_signature", $edit ? $reply['signature'] : 1);
		
		$inputs[] = $this->creator->input_hidden("replying", 1);
		$inputs[] = $this->creator->input_text("Reactie", "body", $this->db_access->db_desqlize($reply['body']));
		$inputs[] = $this->creator->header($reply_id ? "Reactie aanpassen" : "Reageren op dit item");
		
		$page->content['replyform'] = $this->creator->create("replyform", $inputs, $_SERVER['REQUEST_URI']);

	}

	function handle_subscriptions($type, $target, $message) {
		global $CONFIG;

		$table = ($type == "DIR") ? "SUBSCRIBE_DIR" : "SUBSCRIBE_ITEM";
		$target_field = ($type == "DIR") ? "dir_id" : "item_id";

		$sql = $this->db_access->db_query_select(array(array('*'), array('nick', 'email')), array($table, 'MEMBER'), "MEMBER.user_id = {$table}.user_id AND {$target_field} = {$target}");
		$subscrs = $this->db_access->db_do_query($sql);
		while ($s = $this->db_access->db_fetch_array($subscrs)) {
			if (1 or ($s['user_id'] != $_SESSION['user_id'])) {
				switch ($s['subscription_id']) {
					case 1: // alerts
						$this->alerter->add_alert($message['alert'], $_SERVER['PATH_INFO'], $s['user_id']);
						break;
					case 2: // internal mail
						$mail = new InternalMail();
						$mail->from = $CONFIG['system_user'];
						$mail->to = $s['user_id'];
						$mail->subject = $message['subject'];
						$mail->body = $message['mail'];
						$mail->send_mail(1);
						break;
					case 3: // email
						mail("{$s['nick']} <{$s['email']}>", $message['subject'], $message['email'], "From: {$CONFIG['mail_from']} <{$CONFIG['admin_email']}>\nReply-To: <{$CONFIG['admin_email']}>\nReturn-Path: <{$CONFIG['admin_email']}>");
						break;
				}
			}
		}
	}

	function generate_list($parent, $level, $keys, $vals, $menu) {
			
		$rank = 0;	
		$space = "";
		for ($i = 0; $i < $level; $i++)
			$space .= "&nbsp;&nbsp;&nbsp;&nbsp;";
		while ($id = @array_shift($menu[$parent]['children'])) {
			if ($menu[$id]['access'] != "DENY") {
				array_push($keys, "$id");
				array_push($vals, $space . $menu[$id]['menuname']);
				list($keys, $vals) = generate_list($id, ($level+1), $keys, $vals, $menu);
			}
		}	
		return array($keys, $vals);
	}
}

?>
